package com.example.project.controller;

import com.example.project.dto.CategoryDTO;
import com.example.project.model.Category;
import com.example.project.model.Result;
import com.example.project.service.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {
    private final CategoryService categoryService;


    /*获取所有分类*/
    @GetMapping
    public Result<List<Category>> getAllCategories() {
        return Result.success(categoryService.getAllCategories());
    }


    /*根据id获取分类*/
    @GetMapping("/{id}")
    public Result<Category> getCategoryById(@PathVariable int id) {
        return Result.success(categoryService.getCategoryById(id));
    }


    /*创建新的分类*/
    @PostMapping
    public Result<Category> createCategory(@Valid @RequestBody CategoryDTO categoryDTO) {
        Category category = new Category();
        category.setName(categoryDTO.getName());
        category.setDescription(categoryDTO.getDescription());
        return Result.success(categoryService.createCategory(category));
    }


    /*更新分类*/
    @PutMapping("/{id}")
    public Result<Category> updateCategory(
            @PathVariable int id,
            @Valid @RequestBody CategoryDTO categoryDTO
    ) {
        Category category = new Category();
        category.setName(categoryDTO.getName());
        category.setDescription(categoryDTO.getDescription());
        return Result.success(categoryService.updateCategory(id, category));
    }


    /*删除分类*/
    @DeleteMapping("/{id}")
    public Result<?> deleteCategory(@PathVariable int id) {
        categoryService.deleteCategory(id);
        return Result.success();
    }


    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }
}
